package cn.fl.warrant.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.httpclient.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.customer.service.ICstBscInfoService;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.condition.PrjBscInfoQueryCondition;
import cn.fl.project.dto.PrjBscInfoDTO;
import cn.fl.project.service.IProjectApiService;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.warrant.service.IArcPostInfoService;
import cn.fl.warrant.service.IArcSwitchDetailService;
import cn.fl.warrant.service.IArcSwitchMainService;
import cn.fl.warrant.vo.ArcPostInfoVO;
import cn.fl.warrant.vo.ArcSwitchDetailVO;
import cn.fl.warrant.vo.ArcSwitchMainVO;
import cn.fl.warrant.vo.ArcSysFlowSHVO;
import fl.warrant.facade.archive.api.IArcLocalContractUserApiService;
import fl.warrant.facade.archive.api.IArcPortNumberApiService;
import fl.warrant.facade.archive.api.IArcSwitchMainApiService;
import fl.warrant.facade.archive.condition.ArcPortNumberQC;
import fl.warrant.facade.archive.condition.ArcPostInfoQC;
import fl.warrant.facade.archive.condition.ArcSwitchMainQC;
import fl.warrant.facade.archive.constant.ArchiveConstants;
import fl.warrant.facade.archive.dto.ArcPortNumberDTO;
/**
 * @Description: 转仓主表控制层
 */
@Controller
@RequestMapping("/archive/arcSwitchMain")
public class ArcSwitchMainController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(ArcSwitchMainController.class);

	/**
	 * ArcSwitchMain 服务层BEAN
	 */
	@Autowired
	private IArcSwitchMainService arcSwitchMainService;
	@Autowired
	private IArcSwitchMainApiService arcSwitchMainApiService;
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;//数据字典
	
	@Autowired
	private IProjectApiService projectApiService;
	@Autowired
	private ICstBscInfoService cstBscInfoService;
	@Autowired
	private IArcLocalContractUserApiService arcLocalContractUserApiService;
	@Autowired
	private IArcPortNumberApiService arcPortNumberApiService;
	@Autowired
	private IArcSwitchDetailService arcSwitchDetailService;
	@Autowired
	private IArcPostInfoService arcPostInfoService;
	
	private Map getParms(HttpServletRequest request){
		Map map=new HashMap();
		Enumeration enu=request.getParameterNames();  
		StringBuffer sb = new StringBuffer();
		while(enu.hasMoreElements()){  
		String paraName=(String)enu.nextElement();  
			map.put(paraName, request.getParameter(paraName));
		}
		return map;
	}
	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/arcSwitchMain/arcSwitchMainList");
		String sysCd=ArchiveConstants.SYS_CODE, orgCd=ArchiveConstants.ORG_CODE;
		List<KeyValueVO> statusList = this.sysDictionaryApiService.getKvList("ARC028", sysCd, orgCd);//转仓状态
		List<KeyValueVO> payTStatusNmList = this.sysDictionaryApiService.getKvList("PRJ0037", sysCd, orgCd);//支付表状态
		// 事业部
		List<KeyValueVO> buOrgList = this.cstBscInfoService
						.searchBusinessOrgList();
		//List<KeyValueVO> buOrgList = this.sysDictionaryApiService.getKvList(ArchiveConstants.BU_ORG_CD, sysCd, orgCd);//所属机构
		List<KeyValueVO> flowPlaceList = this.sysDictionaryApiService.getKvList("ARC025", sysCd, orgCd);//归档地点
		view.addObject("statusList",statusList);
		view.addObject("payTStatusNmList",payTStatusNmList);
		view.addObject("buOrgList",buOrgList);
		view.addObject("flowPlaceList",flowPlaceList);
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(ArcSwitchMainQC qc,HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String belongCity = request.getParameter("belongCity");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		
		if (StringUtils.isNotEmpty(belongCity)) {
			//TODO SOMTHING
//			ArcLocalContractUserQC aqc=new ArcLocalContractUserQC();
//			aqc.setBelongCity(belongCity);
//			List<ArcLocalContractUserDTO>  list=this.arcLocalContractUserApiService.searchList(aqc, "", "");
//			if (list!=null&&list.size()>0) {
//				
//			}
		}
		
		page.setCondition(qc);
		
		//TODO SOMETHING
		Pager pager = this.arcSwitchMainService.searchListPage(page);
		List<ArcSwitchMainVO> list = (List<ArcSwitchMainVO>) pager.getResultList();
		ListPageVO<ArcSwitchMainVO> listPage = new ListPageVO<ArcSwitchMainVO>(list, pager.getTotalCount());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	/**
	 * 到转仓流程发起页面
	 */
	@RequestMapping(value = "/toFlow.do", method = { RequestMethod.GET})
	public ModelAndView toFlow(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("archive/arcSwitchMain/arcSwitchToFlow");
		String contractNo = request.getParameter("contractNo");
		if (StringUtils.isBlank(contractNo)) {
			return null;
		}
		ArcSwitchMainQC qc=new ArcSwitchMainQC();
		qc.setContractNo(contractNo);
		//获取权证信息
		List<ArcSwitchMainVO> list= this.arcSwitchMainService.searchListForFlow(qc);
		if (list==null||list.size()<1) {
			DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_NO, "条件不满足，不能发起申请！");
			
			view=new ModelAndView("archive/info");
			view.addObject("result",result);
			return view;
		}
		//获取支付表项目信息
		PrjBscInfoQueryCondition qc1=new PrjBscInfoQueryCondition();
		qc1.setCntNo(contractNo);
		List<PrjBscInfoDTO> bDtos=this.projectApiService.searchList(qc1,
				CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
		view.addObject("prjbsc",bDtos.get(0));
		view.addObject("list",list);
		view.addObject("alist",JSON.toJSON(list));
		view.addObject("switchvo",list.get(0));
		BaseLogUtils.info(logger, "toFlow", "到转仓流程发起页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			this.arcSwitchMainService.removeById(Long.valueOf(id));
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.error(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			ArcSwitchMainVO vo = this.arcSwitchMainService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]"+ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}

	/**
	 * 新增流程
	 */
	@RequestMapping(value = "/add.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object add(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "流程发起成功");
		ArcSwitchMainQC entity=null;
		try {
			String contractNo = request.getParameter("contractNo");
			entity = new ArcSwitchMainQC();
			entity.setContractNo(contractNo);
			Map map=this.getParms(request);
			String alist = request.getParameter("alist");
			List<ArcSwitchMainVO> list=JSON.parseArray(alist, ArcSwitchMainVO.class);
			//TODO ADD PARAM
			//List<ArcSwitchMainVO> list= this.arcSwitchMainService.searchListForFlow(entity);
			if (list!=null) {
				for (int i = 0; i < list.size(); i++) {
					ArcSwitchMainVO svo=list.get(i);
					svo.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
					svo.setCrtUsrName(CurrentThreadContext.getCurrentUserName());
					if (svo.getDlist()!=null&&svo.getDlist().size()>0) {
						int count=0;
						for (ArcSwitchDetailVO dvo:svo.getDlist()) {
							if (1==dvo.getIsValid()
									&&"true".equals(map.get("checkCount_p_"+dvo.getPaylistCode()+"_"+dvo.getArcReceiptDetailId()))) {
								if (StringUtils.isNotBlank((String)map.get("thisCount_p_"+dvo.getPaylistCode()+"_"+dvo.getArcReceiptDetailId()))) {
									Long  nLong=Long.parseLong((String)map.get("thisCount_p_"+dvo.getPaylistCode()+"_"+dvo.getArcReceiptDetailId()));
									//if (nLong>0) {
										count++;
									//}
									dvo.setSwitchCount(nLong);
								}
							}else {
								dvo.setSwitchCount(0L);
								dvo.setIsValid(0);
								dvo.setPlaceEnd(null);
								dvo.setPlaceEndNm(null);
							}
						}
						if (count==0) {
							list.remove(i);
							i--;
						}
					}
				}
			}
			if (list.size()<1) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo("无归档数据");				
				return  result;
			}
			DataResultDTO re=this.arcSwitchMainService.addFlow(list);
			result.setInfo(re.getInfo());
			//result.setData(id);
			BaseLogUtils.info(logger, "add", "新增数据.[id=] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "add", "新增数据失败.DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String name = request.getParameter("name");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		ArcSwitchMainVO entity = null;
		try {
			entity = new ArcSwitchMainVO();
			entity.setId(Long.valueOf(id));
			//entity.setName(name);
			//TODO ADD PARAM
			boolean success = this.arcSwitchMainService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity) + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
		}
		return result;
	}
	
	/**
	 * 到流程页面
	 */
	@RequestMapping(value = "/toViewFlow.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toViewFlow(HttpServletRequest request, HttpServletResponse response) {
		String paylistCode = request.getParameter("paylistCode");
		ModelAndView view = new ModelAndView("archive/arcSwitchMain/arcSwitchFlowList");
		view.addObject("paylistCode", paylistCode);
		BaseLogUtils.info(logger, "toViewFlow", "跳转到页面.[paylistCode="+paylistCode+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 流程数据
	 * @param request
	 * @param response
	 * @return
	 * 2018年3月15日 
	 * lxb
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initFlowList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initFlowList(ArcSwitchMainQC qc,HttpServletRequest request, HttpServletResponse response) {
//		String currentPage = request.getParameter("page");
//		String pageSize = request.getParameter("pagesize");
//		String searchName = request.getParameter("demo.name");
		String paylistCode = request.getParameter("paylistCode");
		if (StringUtils.isBlank(paylistCode)) {
			return null;
		}
		//ArcSwitchMainQC qc=new ArcSwitchMainQC();
		qc.setPaylistCode(paylistCode);
		List<ArcSysFlowSHVO> list=this.arcSwitchMainService.searchSwitchFlow(qc);
		ListPageVO<ArcSysFlowSHVO> listPage = new ListPageVO<ArcSysFlowSHVO>(list, list.size());
		BaseLogUtils.info(logger, "initFlowList", "查询数据完成. DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	/**
	 * 支付表明细数据
	 * @param request
	 * @param response
	 * @return
	 * 2018年3月15日 
	 * lxb
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/initArchiveList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initArchiveList(HttpServletRequest request, HttpServletResponse response) {
//		String currentPage = request.getParameter("page");
//		String pageSize = request.getParameter("pagesize");
//		String searchName = request.getParameter("demo.name");
		String paylistCode = request.getParameter("paylistCode");
		if (StringUtils.isBlank(paylistCode)) {
			return null;
		}
		ArcSwitchMainQC qc=new ArcSwitchMainQC();
		qc.setPaylistCode(paylistCode);
		//获取权证信息
		List<ArcSwitchMainVO> list= this.arcSwitchMainService.searchListForFlow(qc);
		BaseLogUtils.info(logger, "initFlowList", "查询数据完成. DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
		if (list!=null&&list.size()>0) {
			List<ArcSwitchDetailVO> dList=list.get(0).getDlist();
			return new ListPageVO<ArcSwitchDetailVO>(dList, dList.size());
		}else {
			return new ListPageVO<ArcSwitchMainVO>(list, list.size());
		}
	}
	/**
	 * 到转仓流程附加信息页面   flag=101总公司邮寄   flag=102省公司邮寄  flag=103合同管理员属地确认上架  flag=104合同管理员总部确认上架
	 */
	@RequestMapping(value = "/toFlowN.do", method = { RequestMethod.GET})
	public ModelAndView toFlowN(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");//PKID 上级id流程用id
		String flag = request.getParameter("flag");
		
		ModelAndView view = new ModelAndView("archive/arcSwitchMain/arcSwitchToFlowN");
		if (StringUtils.isBlank(id)) {
			return null;
		}
		ArcSwitchMainQC qc=new ArcSwitchMainQC();///**上级id流程用id pkid;
		qc.setPkid(id); 
		//获取权证信息
		List<ArcSwitchMainVO> list= this.arcSwitchMainService.searchList(qc);
		BaseLogUtils.info(logger, "toFlowN", "list:"+JSONObject.toJSONString(list));
		if(CollectionUtils.isEmpty(list)) {
			return null;
		}
		Collections.sort(list, comparator);
		ArcSwitchMainVO entity = list.get(0);
		if(StringUtils.isEmpty(entity.getContractNo())) {
			return null;
		}
		//获取邮寄信息
		List<ArcPostInfoVO> plist=new ArrayList<ArcPostInfoVO>();
		ArcPostInfoQC condition2=new ArcPostInfoQC();
		condition2.setArcAppId(Long.valueOf(id));
		plist=this.arcPostInfoService.searchList(condition2);
		//初始化
		if (plist!=null) {
			for (int i = 0; i < plist.size(); i++) {
				ArcPostInfoVO post=plist.get(i);
				//总公司邮寄信息
				if ("101".equals(flag)&& "3".equals(post.getSendPorsonType())) {
					view.addObject("post",post);
					plist.remove(i);
					break;
				}
				//省公司邮寄信息
				if ("102".equals(flag)&& "2".equals(post.getSendPorsonType())) {
					view.addObject("post",post);
					plist.remove(i);
					break;
				}
			}
		}
		view.addObject("plist",plist);
		//获取支付表项目信息
		PrjBscInfoQueryCondition qc1=new PrjBscInfoQueryCondition();
		qc1.setCntNo(entity.getContractNo());
		List<PrjBscInfoDTO> bDtos=this.projectApiService.searchList(qc1,
				CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
		view.addObject("prjbsc",bDtos.get(0));
		view.addObject("list",list);
		view.addObject("switchvo",list.get(0));
		view.addObject("flag",flag);//节点标识
		view.addObject("pkId",id);
		view.addObject("sendTypeList", this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC010,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));//接收方式
		view.addObject("sendCompanyList", this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC012,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));//邮寄公司
		view.addObject("localList", this.sysDictionaryApiService.getKvList(ArchiveConstants.ARC_LOCAL_CITY,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));//属地城市
		BaseLogUtils.info(logger, "toFlow", "转仓流程附加信息页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}
	/**
	 * 转仓流程附加信息页面 更新保存信息
	 */
	@RequestMapping(value = "/modifyFlow.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modifyFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String pkId = request.getParameter("pkId");
		String flag = request.getParameter("flag");//flag=101总公司邮寄   flag=102省公司邮寄
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(pkId)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modifyFlow", "修改数据,主键不存在.[pkId="+pkId+"]flag="+flag, CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		
	   try {
		Map map=this.getParms(request);
		ArcSwitchMainQC qc=new ArcSwitchMainQC();///**上级id流程用id pkid;
		qc.setPkid(pkId); 
		//获取权证信息
		List<ArcSwitchMainVO> list= this.arcSwitchMainService.searchList(qc);
		//取值属地城市简称
		String placeEnd="";
		if(CollectionUtils.isNotEmpty(list)){
			for(int i = 0; i < list.size(); i++) {
				ArcSwitchMainVO mainVO=list.get(i);//thisCount_c_code_2012011942000201: "1"
				//获取权证资料明细
				List<ArcSwitchDetailVO> dlist=mainVO.getDlist();
				if(CollectionUtils.isNotEmpty(dlist)) {
					for(int k = 0; k < dlist.size(); k++) {
						ArcSwitchDetailVO detailVO= dlist.get(k);
						ArcSwitchDetailVO upDetailVO =new ArcSwitchDetailVO();
						upDetailVO.setId(detailVO.getId());
						upDetailVO.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
						upDetailVO.setMdfTm(new Date());
						if(StringUtils.isNotEmpty(detailVO.getPlaceEnd())) {
							placeEnd=detailVO.getPlaceEnd();
						}
						if("101".equals(flag) || "102".equals(flag)) {//总公司邮寄 省公司邮寄  更新转仓份数
							if (map.get("thisCount_c_code_"+detailVO.getId())!=null&&!"".equals(map.get("thisCount_c_code_"+detailVO.getId()))) {
								upDetailVO.setSwitchCount(Long.valueOf(map.get("thisCount_c_code_"+detailVO.getId()).toString().replaceAll(" ", "")));
							}
						}
						if("103".equals(flag) || "104".equals(flag)){//属地总部/省公司  更新上架份数 /归档地点（终）
							if (map.get("thisCountSj_c_code_"+detailVO.getId())!=null&&!"".equals(map.get("thisCountSj_c_code_"+detailVO.getId()))) {
								upDetailVO.setSwitchCountSj(Long.valueOf(map.get("thisCountSj_c_code_"+detailVO.getId()).toString().replaceAll(" ", "")));
							}
							if (map.get("placeEnd_"+detailVO.getId())!=null&&!"".equals(map.get("placeEnd_"+detailVO.getId()))) {
								upDetailVO.setPlaceEnd(map.get("placeEnd_"+detailVO.getId()).toString().replaceAll(" ", ""));
							}
							if("103".equals(flag)) {
								if(map.get("placeEnd_"+detailVO.getId())!=null&&!"".equals(map.get("placeEnd_"+detailVO.getId()))) {
									placeEnd=map.get("placeEnd_"+detailVO.getId()).toString().replaceAll(" ", "");
								}
							}
						}
						arcSwitchDetailService.modify(upDetailVO);
					}
				}
			}
			//flag 103  104 合同管理员属地  可生成省公司档案编号
			if("103".equals(flag)){
				ArcSwitchMainVO mainVO= list.get(0);
				if(StringUtils.isNotBlank(mainVO.getContractNo())) {//根据合同号查询转仓主表，遍历是否有省公司档案编号；有，更新；无，重新生成，更新
					String contractNo=mainVO.getContractNo();
					String portfolioNumberProvince="";//转仓后的省公司档案编号
					ArcSwitchMainQC qcc=new ArcSwitchMainQC();//
					qcc.setContractNo(contractNo);
					//根据合同号获取权证信息
					List<ArcSwitchMainVO> alllist= this.arcSwitchMainService.searchList(qcc);
					if(CollectionUtils.isNotEmpty(alllist)){
						for(ArcSwitchMainVO main:alllist ){
							if(StringUtils.isNotBlank(main.getPortfolioNumberProvince())){
								portfolioNumberProvince=main.getPortfolioNumberProvince();
								break;
							}
						}
					}
					if(StringUtils.isNotEmpty(portfolioNumberProvince)){//根据合同号更新省公司档案编号
						for(ArcSwitchMainVO main:alllist ){
							ArcSwitchMainVO upMain =new ArcSwitchMainVO();
							upMain.setId(main.getId());
							upMain.setPortfolioNumberProvince(portfolioNumberProvince);
							upMain.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
							upMain.setMdfTm(new Date());
							BaseLogUtils.info(logger, "modifyFlow", "更新portfolioNumberProvince"+portfolioNumberProvince, CurrentThreadContext.getCurrentUserName());
							this.arcSwitchMainService.modify(upMain);
						}
					}else {//生成省公司档案编号，根据合同号更新
						String code=createPortfolioNumber(placeEnd);
						for(ArcSwitchMainVO main:alllist ){
							ArcSwitchMainVO upMain =new ArcSwitchMainVO();
							upMain.setId(main.getId());
							upMain.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
							upMain.setMdfTm(new Date());
							upMain.setPortfolioNumberProvince(code);
							BaseLogUtils.info(logger, "modifyFlow", "更新code"+code, CurrentThreadContext.getCurrentUserName());
							this.arcSwitchMainService.modify(upMain);
						}
					}
				}
			}
		}
		//保存邮寄信息flag=101总公司邮寄   flag=102省公司邮寄
		ArcPostInfoVO pVo=new ArcPostInfoVO();
		pVo.setArcAppId(Long.valueOf(pkId));
		//保存邮寄信息
		map.put("arcAppId", pkId);
		map.put("arcAppType", "4");//ARC008
		if("102".equals(flag)){
			//省公司邮寄
			map.put("sendPorsonType", "2");
			map.put("arcAppBussType", "2");
		}else if("101".equals(flag)) {
			//总公司邮寄
			map.put("sendPorsonType", "3");
			map.put("arcAppBussType", "3");
		}
		this.arcPostInfoService.addOrUpdate(map);
		result.setSuccess(BaseConstant.IS_YESNO_YES);
		BaseLogUtils.info(logger, "modifyFlow", "修改成功.[id="+pkId+"] DATA:" + JSONObject.toJSONString(null), CurrentThreadContext.getCurrentUserName());
	}catch (BaseException ex) {
		result.setSuccess(BaseConstant.IS_YESNO_NO);
		result.setInfo(ex.getMessage());
		BaseLogUtils.info(logger, "modifyFlow", "修改失败.[id="+pkId+"] DATA:"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
	}catch (Exception ex) {
		result.setSuccess(BaseConstant.IS_YESNO_NO);
		result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
		BaseLogUtils.error(logger, "modifyFlow", "修改失败.[id="+pkId+"] DATA:"  + ex.getMessage(), CurrentThreadContext.getCurrentUserName());
	}
	return result;
	}
	/**
	 *    生成转仓后的省公司档案袋编号 
	 *    配置化信息规则：所在省简写+所在城市简写 +4位年份+6位编码（顺序累加，满999999后再次从1累加）
		武汉    HBWH202000001          HB WH 2021 10000
	 * @param cityJX 省份城市简写code 如：HBWH
	 * @return
	 * @throws BaseException
	 */
	public String createPortfolioNumber(String cityJX) throws BaseException{
		String portfolioNumber=cityJX;
		if (StringUtils.isNotEmpty(cityJX)) {
			//4位年份
			String date=DateUtil.formatDate(new Date(), "YYYY");
			portfolioNumber=portfolioNumber+date;
			//6位编码
			ArcPortNumberQC qcc =new ArcPortNumberQC();
			qcc.setCityCode(cityJX);
			ArcPortNumberDTO portDTO= arcPortNumberApiService.selectNum(qcc);
			Long num=portDTO.getNum();
			String nums=String.format("%06d", num);
			BaseLogUtils.info(logger, "createPortfolioNumber", "nums" + nums, CurrentThreadContext.getCurrentUserName());
			return cityJX+date+nums;
		}
		return portfolioNumber;
	}
	@RequestMapping(value = "/autoAddSwitchFlow.do", method = { RequestMethod.GET})
	public String autoAddSwitchFlow(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		this.arcSwitchMainApiService.autoAddSwitchFlow();
		return "1";
	}
	Comparator<ArcSwitchMainVO> comparator = new Comparator<ArcSwitchMainVO>() {
        @Override
        public int compare(ArcSwitchMainVO o1, ArcSwitchMainVO o2) {
        	String str1="";String str2="";
        	if(StringUtils.isNotEmpty(o1.getPaylistCode())) {
        		str1=o1.getPaylistCode();
        	}
        	if(StringUtils.isNotEmpty(o2.getPaylistCode())) {
        		str2=o2.getPaylistCode();
        	}
            if(str1.compareTo(str2)>1){
                return  1 ;
            }else if(str1.compareTo(str2)>=0){
            	return -0 ;
            }else{
                return -1 ;
            }
        }
	};
}

